<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package  	PyroCMS
 * @subpackage  Categories
 * @category  	Module
 * @author  	PyroCMS Dev Team
 */
class Admin extends Admin_Controller {

	/**
	 * The current active section
	 * @access protected
	 * @var int
	 */
	protected $section = 'prizes';
	protected $_path = '';
	protected $_folder = '';
	protected $_allowExtension = '';
	protected $_maxSize = '';
	protected $_maxWidth = '';
	protected $_maxHeight = '';
	protected $_thumbWidth = '';
	protected $_thumbHeight = '';
	/**
	 * Array that contains the validation rules
	 * @access protected
	 * @var array
	 */
	protected $validation_rules = array(
		array(
			'field' => 'name',
			'label' => 'lang:escort_country_name_title',
			'rules' => 'trim|required|min_length[2]|max_length[200]|callback__check_name'
		),
		array(
			'field' => 'status',
			'label' => 'lang:escort_country_status_title'
		),
	);
	
	/**
	 * The constructor
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('escort_born_countries_m');
		$this->lang->load('country');
		$this->config->load('country');
		$this->_folder = $this->config->item('upload_image_path');
		$this->_path = FCPATH . $this->config->item('upload_image_path');
		$this->_allowExtension = $this->config->item('files_allowed_file_ext');
		$this->_maxSize = $this->config->item('max_size');
		$this->_maxWidth = $this->config->item('max_width');
		$this->_maxHeight = $this->config->item('max_height');
		$this->_thumbWidth = $this->config->item('thumb_width');
		$this->_thumbHeight = $this->config->item('thumb_height');
		
		// Load the validation library along with the rules
		$this->load->library('form_validation');
		$this->form_validation->set_rules($this->validation_rules);
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('escort.country.js', 'country'))
						->append_metadata(css('escort.country.css', 'country'));
	}
	
	/**
	 * Index method, lists all categories
	 * @access public
	 * @return void
	 */
	public function index()
	{
		$this->pyrocache->delete_all('modules_m');
		
		// Create pagination links
		$total_rows = $this->escort_born_countries_m->count_all();
		$pagination = create_pagination('admin/country/index', $total_rows, NULL, 4);
			
		// Using this data, get the relevant results
		$countries = $this->escort_born_countries_m->order_by('created_time', 'DESC')->limit($pagination['limit'])->get_all();

		$this->template
			->title($this->module_details['name'], lang('escort_country_list_title'))
			->set('imagePath', $this->_path)
			->set('imageFolder', $this->_folder)
			->set('thumbWidth', $this->_thumbWidth)
			->set('thumbHeight', $this->_thumbHeight)
			->set('countries', $countries)
			->set('pagination', $pagination)
			->build('admin/index', $this->data);
	}
	
	/**
	 * Create method, creates a new category
	 * @access public
	 * @return void
	 */
	public function create()
	{
		// Validate the data
		if ($this->form_validation->run())
		{
			
			if($_FILES['image']['name']){
				$config['upload_path'] = $this->_path;
				$config['allowed_types'] = $this->_allowExtension;
				$config['max_size']	= $this->_maxSize;
				$config['max_width']  = $this->_maxWidth;
				$config['max_height']  = $this->_maxHeight;
				
				$this->load->library('upload', $config);
				
				if ($this->upload->do_upload('image'))
				{
					$imageData = $this->upload->data();
					$image = $imageData['file_name'];
					$alt_image =  $this->input->post('title');
					$status = $this->input->post('status');
					if($status){
						$status = 1;
					}else{
						$status = 0;
					}
					$id = $this->escort_born_countries_m->insert(array(
						'name'			=> $this->input->post('name'),
						'image'			=> $image,
						'status'		=> $status
					));
					
					if($id){
						$this->session->set_flashdata('success', sprintf( lang('escort_country_create_success_label'), $this->input->post('name')));
						 redirect('admin/country');
					}else{	
						$this->data->message = lang('escort_country_create_error_label');
					}
				}else{
					$this->data->message = lang('escort_country_upload_error_label');
				}
			}else{
				$this->data->message = lang('escort_country_image_required_label');
			}
		}
		
		// Loop through each validation rule
		foreach ($this->validation_rules as $rule)
		{
			$country->{$rule['field']} = set_value($rule['field']);
		}
		
		$this->template
			->title($this->module_details['name'], lang('escort_country_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->set('country', $country)
			->build('admin/form', $this->data);	
	}
	
	/**
	 * Edit method, edits an existing category
	 * @access public
	 * @param int id The ID of the category to edit
	 * @return void
	 */
	public function edit($id = 0)
	{	
		// Get the category
		$country = $this->escort_born_countries_m->get($id);
		
		// ID specified?
		$country or redirect('admin/country');
		$this->form_validation->set_rules(array_merge($this->validation_rules, array(
			'name' => array(
				'field' => 'name',
				'label' => 'lang:escort_country_name_title',
				'rules' => 'trim|required|min_length[6]|max_length[200]|callback__check_name['.$id.']'
			)
		)));
		// Validate the results
		if ($this->form_validation->run())
		{	
			if($_FILES['image']['name']){
				$config['upload_path'] = $this->_path;
				$config['allowed_types'] = $this->_allowExtension;
				$config['max_size']	= $this->_maxSize;
				$config['max_width']  = $this->_maxWidth;
				$config['max_height']  = $this->_maxHeight;
				
				$this->load->library('upload', $config);
				
				if ($this->upload->do_upload('image'))
				{
					$imageData = $this->upload->data();
					$image = $imageData['file_name'];
					$alt_image =  $this->input->post('title');
					if(file_exists($this->_path.$banner->image)){
						unlink($this->_path.$banner->image);
					}
					$this->load->library('image_lib');
					$imageData = $this->image_lib->explode_name($banner->image);
					if(file_exists($this->_path.$imageData['name'].'_thumb'.$imageData['ext'])){
						unlink($this->_path.$imageData['name'].'_thumb'.$imageData['ext']);
					}
					$status = $this->input->post('status');
					if($status){
						$status = 1;
					}else{
						$status = 0;
					}
					$result = $this->escort_born_countries_m->update($id, array(
						'name'			=> $this->input->post('name'),
						'image'			=> $image,
						'status'			=> $status
					));
					
					if($result){
						$this->session->set_flashdata('success', sprintf( lang('escort_country_edit_success_label'), $this->input->post('name')));
						 redirect('admin/country');
					}else{	
						$this->data->message = lang('escort_country_edit_error_label');
					}
				}else{
					$this->data->message = lang('escort_country_upload_error_label');
				}
			}else{
				$status = $this->input->post('status');
				if($status){
					$status = 1;
				}else{
					$status = 0;
				}
				$result = $this->escort_born_countries_m->update($id, array(
					'name'			=> $this->input->post('name'),
					'status'			=> $status
				));
				
				if($result){
					$this->session->set_flashdata('success', sprintf( lang('escort_country_edit_success_label'), $this->input->post('name')));
					 redirect('admin/country');
				}else{	
					$this->data->message = lang('escort_country_create_error_label');
				}
			}
		}
		
		// Loop through each rule
		foreach ($this->validation_rules as $rule)
		{
			if ($this->input->post($rule['field']) !== FALSE)
			{
				$country->{$rule['field']} = $this->input->post($rule['field']);
			}
		}

		$this->template
			->title($this->module_details['name'], sprintf(lang('escort_country_edit_title'), $country->name))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->set('country', $country)
			->build('admin/form');
	}	

	/**
	 * Delete method, deletes an existing category (obvious isn't it?)
	 * @access public
	 * @param int id The ID of the category to edit
	 * @return void
	 */
	public function delete($id = 0)
	{	
		$id_array = (!empty($id)) ? array($id) : $this->input->post('action_to');
		
		// Delete multiple
		if (!empty($id_array))
		{
			$deleted = 0;
			$to_delete = 0;
			foreach ($id_array as $id)
			{
				if($banner = $this->escort_born_countries_m->get($id)){
					$this->escort_born_countries_m->delete($id);
					$this->load->library('image_lib');
					$imageData = $this->image_lib->explode_name($banner->image);
					$deleted++;
					if(file_exists($this->_path.$banner->image)){
						unlink($this->_path.$banner->image);
					}
					if(file_exists($this->_path.$imageData['name'].'_thumb'.$imageData['ext'])){
						unlink($this->_path.$imageData['name'].'_thumb'.$imageData['ext']);
					}
				}else{
					$this->session->set_flashdata('error', lang('escort_country_deleted_error_label'), $id);
				}
				$to_delete++;
			}
			
			if ( $deleted > 0 )
			{
				$this->session->set_flashdata('success', lang('escort_country_delete_success_label'));
			}
		}		
		else
		{
			$this->session->set_flashdata('error', lang('escort_country_no_selected_error_label'));
		}
		
		redirect('admin/country/index');
	}
		
	/**
	 * Callback method that checks the title of the category
	 * @access public
	 * @param string title The title to check
	 * @return bool
	 */
	public function _check_name($name = '', $id = 0){
		$this->form_validation->set_message('_check_name', sprintf(lang('escort_country_name_already_existed_title'), $name));
		if($id){
			$this->escort_born_countries_m->where('id !=', $id);
		}
		if($this->escort_born_countries_m->get_by('name',$name)){
			return false;
		}else{
			return true;
		}
	}
	
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/country');
			break;
		}
	}
}